package com.zxmr.webclient.action;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zxmr.domain.account.User;
import com.zxmr.domain.service.UserService;
import com.zxmr.webclient.action.dto.UserLogin;
import com.zxmr.webclient.action.view.FailedJSONView;
import com.zxmr.webclient.action.view.JSONView;
import com.zxmr.webclient.action.view.SuccessJSONView;

@Controller
public class UserController {

	@RequestMapping(value = "/user/login", method = RequestMethod.POST)
	public @ResponseBody JSONView login(@ModelAttribute UserLogin user,HttpServletRequest request,BindingResult bind)
	{
		String validate = user.validate();
		if(!"success".equals(validate))
		{
			FailedJSONView view = new FailedJSONView();
			view.setError(validate);
			return view;
		}
		UserService service = new UserService();
		User u = service.findUser(user.getName());
		if(u == null)
		{
			FailedJSONView view = new FailedJSONView();
			view.setError(user.getName()+" is not exist");
			return view;
		}
		if(!user.getPassword().equals(u.getPassword()))
		{
			return new FailedJSONView("password wrong");
		}
		request.getSession().setAttribute("user", u);
		return new SuccessJSONView("wrokbench");
	}
}
